import importlib
import logging
import os


def init_logger():
    import logging.config
    from .logger import LOGGING

    logging.config.dictConfig(LOGGING)


init_logger()
env = os.environ.get("ENV", "")
logger = logging.getLogger(__name__)


def get_config(base_config, package):

    def add_one_config(config, all_config):
        model = config.__dict__
        try:
            names = config.__all__
        except AttributeError:
            names = [name for name in model]
        all_config.update({name: model[name] for name in names})

    all_config = {}
    base_config_t = importlib.import_module(base_config, package=package)
    add_one_config(base_config_t, all_config)
    if env:
        try:
            env_config = importlib.import_module("." + env, package=package)
            add_one_config(env_config, all_config)
            logger.warning(f"the env:【{env}】load success")
        except Exception as ex:
            if ex.name == f"{package}.{env}":
                logger.warning(f"the env:【{env}】not found, use default config:【{base_config}】")
            else:
                raise ex
    return all_config


def update_config(prefix, all_config):
    if not prefix:
        return
    for ek, ev in os.environ.items():
        if ek.startswith(prefix):
            config = ek[len(prefix):]
            all_config[config] = ev


def set_config(prefix='', base_config='.base', package='package'):
    config_dict = get_config(base_config, package)
    update_config(prefix, config_dict)
    return config_dict
